package com.xiaoma.tpo.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaoma.tpo.domain.TRole;
import com.xiaoma.tpo.domain.TRoleRight;
import com.xiaoma.tpo.domain.TUser;
import com.xiaoma.tpo.domain.TUserRole;
import com.xiaoma.tpo.dto.RoleRightVO;
import com.xiaoma.tpo.dto.TRightVO;
import com.xiaoma.tpo.dto.TRoleVO;
import com.xiaoma.tpo.dto.TUserRoleRightVO;
import com.xiaoma.tpo.dto.TUserRoleVO;
import com.xiaoma.tpo.service.TRightService;
import com.xiaoma.tpo.service.TRoleRightService;
import com.xiaoma.tpo.service.TRoleService;
import com.xiaoma.tpo.service.TUserRoleService;
import com.xiaoma.tpo.service.TUserService;

@Controller
@RequestMapping(value="/authority")
public class AuthorityController {
	/**
	 * TRightService 中的right是权限的意思不是 右边的意思
	 */
	@Autowired
	private TRightService tRightService;
	
	@Autowired
	private TRoleService roleService;
	@Autowired
	private TRoleRightService roleRightService;
	@Autowired
	private TUserService tUserService;
	@Autowired
	private TUserRoleService tUserRoleService;
	
	@InitBinder  
    protected void initBinder(WebDataBinder binder) {  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));  
    } 
	
	/**
	 * 生成主页左侧菜单的权限树结构
	 * @return
	 */
	@RequestMapping(value="/left/mainTree",method=RequestMethod.POST)
	@ResponseBody
	public List<TUserRoleRightVO> getMainTree(String username){
		List<TUserRoleRightVO> tUserRoleRight = tUserService.findUserRoleRightByUsername(username);
		return tUserRoleRight;
	}
	/**
	 * 查询权限树结构
	 * @return
	 */
	@RequestMapping(value="/left/tree",method=RequestMethod.GET)
	@ResponseBody
	public List<TRightVO> getRightLeftTree(){
		List<TRightVO> lTRights = tRightService.getRightLeftTree();
		return lTRights;
	}
	/**
	 * 查看相应ID下所有的权限 递归
	 * @param id
	 * @param value
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/right/detail/{id}",method=RequestMethod.GET)
	@ResponseBody
	public List<TRightVO> getRightDetail(@PathVariable Integer id,String value,HttpServletRequest request){
		//两个页面之间传递treeNode.id的值（rightLeft.jsp => rightRight.jsp）
		List<TRightVO> lTRights =new  ArrayList<TRightVO>();
		if("1".equals(value)){
			request.getSession().setAttribute("id", id);
			return lTRights;
		}
		lTRights = tRightService.getRightLeftTreeById(id);
		return lTRights;
	}
	//添加权限（@RequestBody，表示发送的数据必须为json ,而form表单发送的数据不是json）
	@RequestMapping(value="/right/add",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> rightAdd(@ModelAttribute TRightVO tRightVO){
		Map<String, Object> map = new HashMap<String, Object>();
		//校验 新添加的权限名是否与同级的权限名重复
		if(tRightService.validateRepeat(tRightVO)){
			map.put("status",-2);
			return map;
		}
		tRightService.save(tRightVO);
		map.put("status", true);
		return map;
	}
	//编辑权限
	@RequestMapping(value="/right/edit",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> rightEdit(@ModelAttribute TRightVO tRightVO){
		Map<String, Object> map = new HashMap<String, Object>();
		//校验 新添加的权限名是否与同级的权限名重复
		if(tRightService.validateRepeat(tRightVO)){
			map.put("status",-2);
			return map;
		}
		tRightService.edit(tRightVO);
		map.put("status", true);
		return map;
	}
	//删除权限
	@RequestMapping(value="/right/deleteone",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> rightDelete(@RequestParam Integer id){
		Map<String, Object> map = new HashMap<String, Object>();
		//校验 权限资源是否被角色占用
		if(tRightService.hasRelation(id)){
			map.put("status", -2);
			return map;
		}
		tRightService.delete(id);
		map.put("status", true);
		return map;
	}
	/**
	 * 获取所有的角色组成角色树(供授予用户角色使用)
	 * @return
	 */
	@RequestMapping(value="/role/roleTree",method=RequestMethod.GET)
	@ResponseBody
	public List<TRoleVO> findAllRole(){
		List<TRoleVO> rTRoleVOs = roleService.findAllRole();
		return rTRoleVOs;
	}
	/**
	 * 获取所有的角色
	 * @return
	 */
	@RequestMapping(value="/role/findall",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> getAllRoles(){
		Map<String, Object> result = new HashMap<String,Object>();
		List<TRole> rTRoles = roleService.findAllRoles();
		result.put("rows", rTRoles);
		return result;
	}
	
	//添加角色（@RequestBody，表示发送的数据必须为json ,而form表单发送的数据不是json）
	@RequestMapping(value="/role/add",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> roleAdd(@ModelAttribute TRole role){
		Map<String, Object> map = new HashMap<String, Object>();
		//验证role是不是重复
		if(roleService.validateRole(role,1)){
			map.put("status", -2);
			return map;
		}
		roleService.save(role);
		map.put("status", true);
		return map;
	}
	//编辑角色
	@RequestMapping(value="/role/edit",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> roleEdit(@ModelAttribute TRole TRole){
		Map<String, Object> map = new HashMap<String, Object>();
		//验证role是不是重复
		if(roleService.validateRole(TRole,2)){
			map.put("status", -2);
			return map;
		}
		roleService.edit(TRole);
		map.put("status", true);
		return map;
	}
	//删除角色
	@RequestMapping(value="/role/deleteone",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> roleDelete(@RequestParam Integer id){
		Map<String, Object> map = new HashMap<String, Object>();
		//校验 判断角色是否被使用
		if(roleService.hasRelation(id)){
			map.put("status", -2);
			return map;
		}
		//先删除角色
		roleService.delete(id);
		//在删除 角色和权限的关系表中的相应的关系
		roleService.deleteRelation(id);
		map.put("status", true);
		return map;
	}
	/**
	 * 角色授权
	 */
	@RequestMapping(value="/role/saveRoleRight",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveRoleRight(RoleRightVO roleRightVO){
		Map<String, Object> result = new HashMap<String, Object>();
		roleRightService.saveRoleRight(roleRightVO);
		result.put("status", 1);
		return result;
	}
	/**
	 * 获取相应roleId下的RoleRight所有关系
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/role/getRoleRight",method=RequestMethod.POST)
	@ResponseBody
	public List<TRoleRight> getRoleRightById(@RequestParam Integer roleId){
		List<TRoleRight> lRoleRights = roleRightService.getRoleRightById(roleId);
		return lRoleRights;
	}
	/**
	 * 用户管理
	 * 增加用户
	 */
	@RequestMapping(value="/user/saveUser",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveUser(TUser tUser){
		Map<String, Object> result = new HashMap<String,Object>();
		//判断用户名是否重复
		if(tUserService.validateUser(tUser,1)){
			result.put("status", -2);
			result.put("message", "用户名重复了");
			return result;
		}
		tUserService.save(tUser);
		result.put("status", 1);
		result.put("message", "保存成功");
		return result;
	}
	/**
	 * 
	 * 修改用户
	 */
	@RequestMapping(value="/user/updateUser",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateUser(TUser tUser){
		Map<String, Object> result = new HashMap<String,Object>();
		//判断用户名是否重复
		if(tUserService.validateUser(tUser,2)){
			result.put("status", -2);
			result.put("message", "用户名重复了");
			return result;
		}
		tUserService.update(tUser);
		result.put("status", 1);
		result.put("message", "更新成功");
		return result;
	}
	/**
	 * 
	 * 删除用户
	 */
	@RequestMapping(value="/user/deleteUser",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteUser(Integer id){
		Map<String, Object> result = new HashMap<String,Object>();
		//判断是不是admin如果是则不让删除
		if(tUserService.findById(id)){
			result.put("status", -1);
			result.put("message", "admin不允许删除");
			return result;
		}
		//先删除用户
		tUserService.delete(id);
		//在把 t_user_role 中的关联关系一并删除
		tUserRoleService.delete(id);
		result.put("status", 1);
		result.put("message", "删除成功");
		return result;
	}
	/**
	 * 
	 * 查询用户
	 */
	@RequestMapping(value="/user/findAllUser",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findAllUser(){
		Map<String, Object> result = new HashMap<String,Object>();
		List<TUser> tUsers = tUserService.findAllUser();
		result.put("rows", tUsers);
		return result;
	}
	/**
	 * 
	 * 查询t_user_role 关系
	 */
	@RequestMapping(value="/user/getUserRole",method=RequestMethod.POST)
	@ResponseBody
	public List<TUserRole> findUserRole(Integer userId){
		List<TUserRole> rTUserRoles = tUserRoleService.find(userId);
		return rTUserRoles;
	}
	/**
	 * 
	 * 保存t_user_role 关系
	 */
	@RequestMapping(value="/user/saveUserRole",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveUserRole(TUserRoleVO tUserRoleVO){
		Map<String,Object> result = new HashMap<String,Object>();
		tUserRoleService.save(tUserRoleVO);
		result.put("status", 1);
		return result;
	}
	
}
